package com.anthonyfdev.dropdownviewexample;

import com.anthonyfdev.dropdownviewexample.slice.DropDownAbilitySlice;
import ohos.agp.components.*;

public class DropDownAdapter extends BaseItemProvider {

    private final ViewActions actionViewDelegate;

    public DropDownAdapter(final ViewActions actionViewDelegate) {
        this.actionViewDelegate = actionViewDelegate;
    }

    @Override
    public int getCount() {
        return DropDownAbilitySlice.NUM_OF_STANDS;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Component child = component;
        if (component == null) {
            child = LayoutScatter.getInstance(componentContainer.getContext()).parse(ResourceTable.Layout_list_item_stand_drop_down, componentContainer, false);
        }
        child.setTag(i);
        StandViewHolder holder = new StandViewHolder(child);
        holder.bind(i);
        return child;
    }

    class StandViewHolder {

        private final Component standShadowTV;
        private final Text standTitleTV;
        private final Text standStatusTV;


        public StandViewHolder(Component itemView) {
            standTitleTV = (Text) itemView.findComponentById(ResourceTable.Id_cell_stand_title);
            standStatusTV = (Text) itemView.findComponentById(ResourceTable.Id_cell_stand_status);
            standShadowTV = itemView.findComponentById(ResourceTable.Id_cell_stand_shadow);
            itemView.setClickedListener(standViewItemClickListener);
        }

        public void bind(int position) {
            standTitleTV.setText(actionViewDelegate.getStandTitle(position));
            standStatusTV.setText(actionViewDelegate.getStandStatus(position));

            standShadowTV.setVisibility(actionViewDelegate.getSelectedStand() == position ? Component.VISIBLE : Component.INVISIBLE);
        }

        private final Component.ClickedListener standViewItemClickListener = new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                int lastSelectedPosition = actionViewDelegate.getSelectedStand();
                actionViewDelegate.setSelectedStand((int)(v.getTag()));
                notifyDataSetItemChanged(lastSelectedPosition);
                notifyDataSetItemChanged((int)(v.getTag()));
                actionViewDelegate.collapseDropDown();
            }
        };
    }

    public interface ViewActions {
        void collapseDropDown();
        void setSelectedStand(int standId);
        String getStandTitle(int standId);
        String getStandStatus(int standId);
        int getSelectedStand();
    }
}
